//
//  SYDIdentityInformationViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/7.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDIdentityInformationViewController.h"
#import "YMAddPhotoView.h"
#define identityInfoId @"SYDRegisterCell"

@interface SYDIdentityInformationViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)SYDRegisterHeaderView *registerHeaderView;
@property(nonatomic,strong)SYDRegisterFooterView *registerFooterView;
@property(nonatomic,strong)YMAddPhotoView *addPhotoView;


//二进制数据流
@property (nonatomic, strong) NSData *commentData;

@property(nonatomic,strong)NSString *realName;//名字
@property(nonatomic,strong)NSString *cardId;//电话号码
@property(nonatomic,strong)NSString *iconUrl;//头像
@property(nonatomic,strong)NSString *IDPhotoFrontUrl;//身份证前面
@property(nonatomic,strong)NSString *IDPhotoBackUrl;//身份证后面

@end

@implementation SYDIdentityInformationViewController
#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    WEAKSELF
    [weakSelf backButtonAction:^{
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationBar.title = @"注册";
    [self initInformationeUI];
    [self navigationBarHandle];
}

-(void)initInformationeUI{
    if (@available(iOS 11.0,*)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.realName = @"";
    self.cardId = @"";
    self.iconUrl = @"";
    self.IDPhotoBackUrl = @"";
    self.IDPhotoFrontUrl = @"";
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:identityInfoId bundle:nil] forCellReuseIdentifier:identityInfoId];

    self.tableView.tableHeaderView = self.registerHeaderView;
    self.tableView.tableFooterView = self.registerFooterView;
    //下一步
    self.registerFooterView.nextStepBtn.eventTimeInterval = 3.0;
    [[self.registerFooterView.nextStepBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self UploadUserInfoRegisterToServer];
    }];
    //获取头像
    WEAKSELF
    [[self.registerFooterView.leftImage rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        [SYDPhotoPickerManager shared].maxCount = 1;
        [[SYDPhotoPickerManager shared]showActionSheetInView:self.view fromController:self allowEdit:YES completion:^(UIImage *image) {
           UIImage *newImage =  [UIImage imageWithImage:image scaledToSize:CGSizeMake(160, 100)];
            [weakSelf.registerFooterView.leftImage setImage:newImage forState:UIControlStateNormal];
            //上传图片
            [[SYDNetwork shareTool]uploadMultipartFilesWithParameters:nil mFile:@"mFile" uploadData:UIImageJPEGRepresentation(image, 0.01) success:^(NSURLSessionDataTask *task, id responseObject) {
                @try {
                    //NSLog(@"responseObject:%@",responseObject);
                    if ([responseObject[@"statusCode"]integerValue] == 200) {
                        weakSelf.IDPhotoFrontUrl = responseObject[@"obj"];
                    }
                } @catch (NSException *exception) {
                    NSLog(@"exception:%@",exception.description);
                } @finally {
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                NSLog(@"error:%@",error);
            }];
            
            [weakSelf.tableView reloadData];
        } cancelBlock:^{
            NSLog(@"cancel");
        }];
    }];
    
    [[self.registerFooterView.rightImage rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [SYDPhotoPickerManager shared].maxCount = 1;
        [[SYDPhotoPickerManager shared]showActionSheetInView:self.view fromController:self allowEdit:YES completion:^(UIImage *image) {
            UIImage *newImage =  [UIImage imageWithImage:image scaledToSize:CGSizeMake(160, 100)];
            [weakSelf.registerFooterView.rightImage setImage:newImage forState:UIControlStateNormal];
            //上传图片
            [[SYDNetwork shareTool]uploadMultipartFilesWithParameters:nil mFile:@"mFile" uploadData:UIImageJPEGRepresentation(image, 0.01) success:^(NSURLSessionDataTask *task, id responseObject) {
                @try {
                    //NSLog(@"responseObject:%@",responseObject);
                    if ([responseObject[@"statusCode"]integerValue] == 200) {
                        weakSelf.IDPhotoBackUrl = responseObject[@"obj"];
                    }
                } @catch (NSException *exception) {
                    NSLog(@"exception:%@",exception.description);
                } @finally {
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                NSLog(@"error:%@",error);
            }];
            [weakSelf.tableView reloadData];
        } cancelBlock:^{
            NSLog(@"cancel");
        }];
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SYDRegisterCell *cell = [tableView dequeueReusableCellWithIdentifier:identityInfoId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.userIcon.userInteractionEnabled = YES;
    WEAKSELF
    [cell.userName.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        weakSelf.realName = x;
    }];
    [cell.userIdCard.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        weakSelf.cardId = x;
    }];
    [cell.userIcon jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        
        [SYDPhotoPickerManager shared].maxCount = 1;
        [[SYDPhotoPickerManager shared]showActionSheetInView:self.view fromController:self allowEdit:YES completion:^(UIImage *image) {
            NSLog(@"%@",image);
            cell.userIcon.image = image;
            weakSelf.commentData = UIImageJPEGRepresentation(cell.userIcon.image, 0.01);
            //上传图片
            WEAKSELF
            [[SYDNetwork shareTool]uploadMultipartFilesWithParameters:nil mFile:@"mFile" uploadData:weakSelf.commentData success:^(NSURLSessionDataTask *task, id responseObject) {
                @try {
                    NSLog(@"responseObject:%@",responseObject);
                    if ([responseObject[@"statusCode"]integerValue] == 200) {
                        weakSelf.iconUrl = responseObject[@"obj"];
                    }
                } @catch (NSException *exception) {
                    NSLog(@"exception:%@",exception.description);
                } @finally {
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                NSLog(@"error:%@",error);
            }];
            
            [weakSelf.tableView reloadData];
        } cancelBlock:^{
            NSLog(@"cancel");
        }];
        
    }];
    
    return  cell;

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 168;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    
}

#pragma mark---lazy
-(UITableView *)tableView{
    if (!_tableView) {
        if (iPhone8_X) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 88, SCREEN_WIDTH, SCREEN_HEIGHT - 88) style:UITableViewStylePlain];
        } else {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
        }
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        
    }
    return  _tableView;
}
-(SYDRegisterHeaderView *)registerHeaderView{
    if (!_registerHeaderView) {
        _registerHeaderView = [[SYDRegisterHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 142)];
        _registerHeaderView.headerImage.image = [UIImage imageNamed:@"progress_bar1"];
        _registerHeaderView.titleMessageLbl.text = @"个人信息";
        
    }
    return _registerHeaderView;
}
-(SYDRegisterFooterView *)registerFooterView{
    if (!_registerFooterView) {
        _registerFooterView = [[SYDRegisterFooterView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 266)];
        _registerFooterView.titleLabel.text  = @"上传身份证";
        [_registerFooterView.leftImage setImage:[UIImage imageNamed:@"id_card_front"] forState:UIControlStateNormal];
        [_registerFooterView.rightImage setImage:[UIImage imageNamed:@"id_card_back"] forState:UIControlStateNormal];
    
    }
    return _registerFooterView;
}
-(YMAddPhotoView *)addPhotoView{
    if (!_addPhotoView) {
        _addPhotoView =  [[YMAddPhotoView alloc]init];
    }
    return _addPhotoView;
}

#pragma mark---接口请求
-(void)uploadMultipartFiles{
    
    }
-(void)UploadUserInfoRegisterToServer{
    //身份信息
    WEAKSELF
    if ([self.realName isEqualToString:@""]) {
        [SVProgressHUD displayInfoWithStatus:@"请输入有效真实姓名"];
    }else if ([self.cardId isEqualToString:@""]){
        [SVProgressHUD displayInfoWithStatus:@"请输入身份证"];
    }else if ([self.iconUrl isEqualToString:@""]){
        [SVProgressHUD displayInfoWithStatus:@"请上传本人头像"];
    }else if ([self.IDPhotoFrontUrl isEqualToString:@""]){
        [SVProgressHUD displayInfoWithStatus:@"请上传身份证正面"];
    }else if ([self.IDPhotoBackUrl isEqualToString:@""]){
       [SVProgressHUD displayInfoWithStatus:@"请上传身份证反面"];
    }else{
        [[SYDNetwork shareTool]userInfoRegisterWithRegisterStep:@"1" realName:self.realName cardId:self.cardId iconUrl:self.iconUrl IDPhotoFrontUrl:self.IDPhotoFrontUrl IDPhotoBackUrl:self.IDPhotoBackUrl busBrand:@"" busLicensePlate:@"" busOwner:@"" carPhotoUrl:@"" cityBelong:@"" cityCode:[YMSaveTool valueForKey:CityCode] firmBelong:@"" passengerCountPermitted:@"" drivingLicenceStartTime:@"" drivinglicenceBackUrl:@"" drivinglicenceFrontUrl:@"" runningLicenceRegisterTime:@"" runningLicenceBackUrl:@"" runningLicenceFrontUrl:@"" userId:self.registerID success:^(NSURLSessionDataTask *task, id responseObject) {
            @try {
                NSLog(@"%@",responseObject);
                if ([responseObject[@"statusCode"]integerValue] == 200) {
                    SYDDriverLicenseViewController *driveVc = [[SYDDriverLicenseViewController alloc]init];
                    driveVc.registerID = weakSelf.registerID;
                    [weakSelf.navigationController pushViewController:driveVc animated:YES];
                }else{
                    [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
                }
            } @catch (NSException *exception) {
                NSLog(@"exception:%@",exception.description);
            } @finally {
                
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
            [SVProgressHUD displayInfoWithStatus:@"注册失败,请检查网络..."];
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

